//获取应用实例
const app = getApp()
var util = require('../../utils/util.js');

var apiHost = wx.getStorageSync('apiHost');
var yunId = wx.getStorageSync('yunId');

var goodOrders = new Array();
var createTime = util.formatTime(new Date()).toString();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    mySearch: [],        //最近搜索
    otherSearch: [],       //大家都在搜
    searchValue: '',     //搜索框内容
    hiddenLoading: true,  //是否显示loading
    searchCon: [],       //搜索内容
    scrollTop: 0,         //返回顶部高度
    floorstatus: false,   //返回顶部按钮是否显示
    is_none: false
  },
  //返回顶部高度
  goTop: function (e) {
    this.setData({
      scrollTop: 0
    })
  },
  //监听滑动事件
  scroll: function (e) {
    if (e.detail.scrollTop > 500) {
      this.setData({
        floorstatus: true
      });
    } else {
      this.setData({
        floorstatus: false
      });
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;

    var openId = wx.getStorageSync('openId');     //用户openId获取

    if (openId != '') {
      that.setData({
        openId: openId
      });

      that.gucl();          //初始化购物车
    }

    that.searchM();       //初始化默认
  

  },
  //获取搜索框输入内容
  searchInput: function (e) {
    var that = this;
    that.setData({
      searchValue: e.detail.value
    })
  },
  initHeght: function () {
    var that = this;
    /*获取指定元素高度*/
    var query = wx.createSelectorQuery();
    var shopHeight = "";
    //获取店铺头部高度
    query.select('#searchH').boundingClientRect()
    query.exec(function (res) {
      shopHeight = res[0].height;

      wx.getSystemInfo({
        success: function (res) {
          that.setData({
            searchConHeight: res.windowHeight - shopHeight
          });
        }
      });
    });
  },
  //点击搜索按钮
  searchSubmit: function () {
    var that = this;
    var searVal = that.data.searchValue;    //获取搜索框内容

    //显示loading
    that.setData({
      hiddenLoading: false
    })

    that.searchGoodsName(searVal);  //搜索商品（根据名称）

  },
  //搜索商品（根据名称）
  searchGoodsName: function (name) {
    var that = this;
    wx.request({
      url: apiHost + "/xcx/goods/list/condition",
      data: {
        yunId: yunId,
        openId: that.data.openId,
        name: name
      },
      header: {
        "Content-Type": "application/json"
      },
      success: function (res) {
        var code = res.data.code;
        var msg = res.data.msg

        if (code == "10000") {
          var searchCons = res.data.data.list
          var flag = false
          if (searchCons.length == 0) {
            flag = true;
          } else {
            flag = false;
          }

          that.initHeght(); //计算高度
          that.setData({
            hiddenLoading: true,
            searchCon: searchCons,
            is_none: flag
          })
        }else{
          wx.showToast({
            title: msg,
            icon: 'none',
            duration: 2000,
            mask: true
          });
        }
        

      }
    })
  },

  //点击历史搜索
  clickNameNow: function (e) {
    var that = this;
    var name = e.currentTarget.dataset.toggle;
    that.setData({
      searchValue: name
    })
    that.searchGoodsName(name);  //搜索商品（根据名称）
  },
  //搜索默认
  searchM: function () {
    var that = this;

    wx.request({
      url: apiHost + "/xcx/search/index",
      data: {
        yunId: yunId,
        openId: that.data.openId
      },
      header: {
        "Content-Type": "application/json"
      },
      success: function (res) {
        var code = res.data.code;
        var msg = res.data.msg

        if (code == "10000") {
          var searchList = res.data.data;

          that.setData({
            otherSearch: searchList.otherSearch,
            mySearch: searchList.mySearch
          });
        }else{
          wx.showToast({
            title: msg,
            icon: 'none',
            duration: 2000,
            mask: true
          });
        }

      }
    })
  },
  //初始化购物车
  gucl: function (e) {
    var that = this;

    //购物车列表
    wx.request({
      url: apiHost + "/xcx/userShoppingCart/list",
      data: {
        yunId: yunId,
        openId: that.data.openId
      },
      header: {
        "Content-Type": "application/json"
      },
      success: function (res) {
        var countCarts = 0;

        var code = res.data.code;
        var msg = res.data.msg

        if (code == "10000") {
          var CartsList = res.data.data.list;
          //循环遍历所有购物车的数量
          for (var a = 0; a < CartsList.length; a++) {
            countCarts += CartsList[a].count
          }
          that.setData({
            gwclist: CartsList,
            carts: countCarts
          });

          //总价
          var newList = that.data.gwclist
          var newaa = 0
          for (var i = 0; i < newList.length; i++) {
            newaa += newList[i].count * newList[i].price
          }

          that.setData({
            zong: newaa.toFixed(2),
          })
        }else{
          wx.showToast({
            title: msg,
            icon: 'none',
            duration: 2000,
            mask: true
          });
        }
      }
    })

  },
  // 购物车的显示隐藏
  showcart: function (e) {
    var that = this;


    that.setData({
      showModall: true,
    })


  },
  //隐藏购物车的++
  addd: function (e) {
    var that = this
    var gou = e.target.dataset.toggle;//获取的拼接
    var gouList = gou.split(",");//以逗号截取
    var spuId = gouList[0];
    var price = gouList[1];
    var count = gouList[2];
    var index = parseInt(e.currentTarget.dataset.index);
    var numm = parseInt(e.currentTarget.dataset.count)

    that.setData({
      numm: parseInt(count) + 1,
    })
    var count = that.data.numm
    that.addCart(spuId, count);//计算购物车数量

  },
  /**
   * 计算购物车数量
   */
  addCart: function (spuId, count) {
    var that = this
    wx.showLoading({
      title: '加载中',
      icon: 'loading',
    });

    wx.request({
      url: apiHost + "/xcx/userShoppingCart/add",
      data: {
        openId: that.data.openId,
        yunId: yunId,
        spuId: spuId,
        count: count
      },
      header: {
        "Content-Type": "application/json"
      },
      success: function (res) {
        that.gucl();
        that.searchSubmit();//初始化搜索
        wx.hideLoading();   //隐藏加载loading
      }
    })
  },
  //隐藏购物车的--
  minuss: function (e) {
    var that = this
    var gou = e.target.dataset.toggle;//获取的拼接
    var gouList = gou.split(",");//以逗号截取
    var spuId = gouList[0];
    var price = gouList[1];
    var count = gouList[2];
    var cartId = gouList[3];
    var index = parseInt(e.currentTarget.dataset.index);
    var numm = parseInt(e.currentTarget.dataset.count)
    that.setData({
      numm: parseInt(count) - 1,
    })
    var count = that.data.numm

    if (count == 0) {
      that.removeShopCart(cartId);//如果等于0 直接删除当前商品购物车
    } else {
      that.addCart(spuId, count);//计算购物车数量
    }

  },


  //删除购物车（当前商品在购物车）
  removeShopCart: function (cartId) {
    var that = this;
    wx.showLoading({
      title: '加载中',
      icon: 'loading',
    });

    wx.request({
      url: apiHost + "/xcx/userShoppingCart/del",
      data: {
        openId: that.data.openId,
        yunId: yunId,
        cartId: cartId
      },
      header: {
        "Content-Type": "application/json"
      },
      success: function (res) {
        that.gucl();
        that.searchSubmit();//初始化搜索
        wx.hideLoading();   //隐藏加载loading
      }
    })
  },
  //打开购物车
  gouwuchez: function () {
    var that = this
    that.setData({
      showModall: true
    })

  },
  //关闭购物车
  gouwuchezz: function () {
    var that = this
    that.setData({
      showModall: false
    })
  },
  // 清空购物车
  qingkong: function () {
    var that = this;

    wx.showLoading({
      title: '加载中',
      icon: 'loading',
    });

    wx.request({
      url: apiHost + "/xcx/userShoppingCart/clear",
      data: {
        openId: that.data.openId,
        yunId: yunId
      },
      header: {
        "Content-Type": "application/json"
      },
      success: function (res) {
        // console.log(res)
        that.gucl();
        that.searchSubmit();//初始化搜索
        wx.hideLoading();   //隐藏加载loading
      }
    })
  },
  //结算
  settlement: function () {
    var that = this
    var newList = that.data.gwclist
    var a = ''
    var json = '';
    var that = this;
    //显示加载动画
    that.setData({
      hiddenLoading: false
    });
    goodOrders = new Array();
    for (var i = 0; i < newList.length; i++) {
      a = {
        spuId: newList[i].spuId,
        count: newList[i].count
      }
      goodOrders.push(a);
    }
    json = JSON.stringify(goodOrders);

    if (goodOrders.length > 0) {
      wx.navigateTo({
        url: '/pages/userOrder/confirm/confirm?goodOrders=' + json + "&yunId=" + yunId + "&openId=" + that.data.openId + "&createTime=" + createTime,
      })
      that.setData({
        goodOrders: json
      })
    }

    that.setData({
      hiddenLoading: true
    });

  },
  // 购物车的显示隐藏
  cart: function (e) {
    var _this = this;
    var getPj = e.target.dataset.toggle;//获取的拼接
    var getPjOb = getPj.split(",");//以逗号截取
    var spuId = getPjOb[0];
    var danjia = getPjOb[1];

    _this.gucl();
    var count = 1
    _this.addCart(spuId, count)

  },

  // 数量的--
  minus: function (e) {
    var _this = this;

    var bianjidizhi = e.target.dataset.toggle;//获取的拼接
    var bianjidizhiList = bianjidizhi.split(",");//以逗号截取
    var spuId = bianjidizhiList[0];
    var danjia = bianjidizhiList[1];
    var num = parseInt(bianjidizhiList[2]);
    var cartId = bianjidizhiList[3];

    _this.setData({
      num: num - 1,
    })
    var count = _this.data.num

    if (count == 0) {
      _this.removeShopCart(cartId);//如果等于0 直接删除当前商品购物车
    } else {
      _this.addCart(spuId, count);//计算购物车数量
    }
  },
  // 数量的++
  add: function (e) {
    var that = this;

    var bianjidizhi = e.target.dataset.toggle;//获取的拼接
    var bianjidizhiList = bianjidizhi.split(",");//以逗号截取
    var spuId = bianjidizhiList[0];
    var danjia = bianjidizhiList[1];
    var num = parseInt(bianjidizhiList[2]);

    var index = parseInt(e.target.dataset.index);
    that.setData({
      num: num + 1,
    })

    var count = that.data.num
    that.addCart(spuId, count);//计算购物车数量
  },



  /**
   * 清除历史搜索
   */
  clearSearch: function () {
    var that = this;

    //商家
    wx.request({
      url: apiHost + "/xcx/search/clear",
      data: {
        yunId: yunId,
        openId: that.data.openId
      },
      header: {
        "Content-Type": "application/json"
      },
      success: function (res) {
        that.searchM();
      }
    })
  },

  /**
   * 修改商品
   */
  updateGoods: function (e) {
    var spuId = e.target.dataset.toggle;

    wx.showToast({
      title: '加载中',
      icon: 'loading',
      mask: true
    })
    wx.navigateTo({
      url: '../goods/goods?spuId=' + spuId
    });
  },

  

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  }
})